﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Modeling;
using System.Diagnostics;

namespace DSLFactory.VSCTDesigner
{
    partial class ExternCommandSerializer
    {
        /// <summary>
        /// Création de la commande (virtuelle) externe
        /// </summary>
        /// <param name="serializationContext"></param>
        /// <param name="reader"></param>
        /// <param name="sourceRolePlayer"></param>
        /// <param name="relDomainClassId"></param>
        /// <param name="partition"></param>
        /// <returns></returns>
        protected override Microsoft.VisualStudio.Modeling.Moniker CreateMonikerInstance(Microsoft.VisualStudio.Modeling.SerializationContext serializationContext, System.Xml.XmlReader reader, Microsoft.VisualStudio.Modeling.ModelElement sourceRolePlayer, Guid relDomainClassId, Microsoft.VisualStudio.Modeling.Partition partition)
        {
            Moniker moniker = base.CreateMonikerInstance(serializationContext, reader, sourceRolePlayer, relDomainClassId, partition);
            string[] parts = moniker.MonikerName.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            Debug.Assert(parts.Length == 2);

            var commandTables = partition.ElementDirectory.FindElements<VSCTDesigner.CommandTable>();
            Command command = sourceRolePlayer as Command;
            if( command != null )
            {
                VSCTDesigner.Commands commands = command.CommandTable.Commands;
                ExternCommand externCommand = commands.ExternCommandAliases.Find(m => m.Guid == parts[0] && m.ID == parts[1]);
                if( externCommand == null )
                {
                    externCommand = new ExternCommand(partition);
                    externCommand.Guid = parts[0];
                    externCommand.ID = parts[1];
                    commands.ExternCommandAliases.Add(externCommand);                    
                }
            }

            return moniker;
        }
    }
}
